const Router = require('koa-router')
const { catchError, generateOk, check } = require('../../lib/check')
const { getAllHotSearches, searchHotSearch, editHotSearch, addHotSearch } = require('../../model/hotSearches')


let hotSearch = new Router()

hotSearch.post('/get', async (ctx) => {
  try {
    const hotSearches = getAllHotSearches()
    ctx.body = generateOk(hotSearches.filter(item => item.statu === 1))
  } catch (e) {
    catchError(e, ctx)
  }
})

hotSearch.post('/add', async (ctx) => {
  try {
    const data = ctx.request.body
    check(data.content, 'Params_lost')
    const findHotSearch = searchHotSearch(data.content)
    if (findHotSearch) {
      editHotSearch({ ...findHotSearch, times: findHotSearch.times + 1 })
      ctx.body = generateOk({ ...findHotSearch, times: findHotSearch.times + 1 })
    } else {
      const param = { 
        content: data.content,
        statu: 1,
        times: 1,
        create_Ts: new Date().getTime().toString()
      }
      addHotSearch(param)
      ctx.body = generateOk(param)
    }
  } catch (e) {
    catchError(e, ctx)
  }
})

module.exports = hotSearch 